package com.kenyi.co.ui.login;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kenyi.co.R;
import com.kenyi.co.common.ui.BaseActivity;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.okhttp.utils.GsonResultok;
import com.kenyi.co.ui.login.Bean.AuthLoginBean;
import com.kenyi.co.ui.login.Bean.TokenBean;
import com.kenyi.co.ui.me.ui.MeFavActivity;
import com.kenyi.co.utils.Config;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.ToastUtil;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

import static com.yanzhenjie.permission.runtime.Permission.READ_PHONE_STATE;

/**
 * 注册页
 */
public class LoginPhoneActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_home_title, tv_login_getcode;
    private Toolbar toolbar;
    private Button bt_login;
    private EditText et_login_code, et_login_phone;
    private Boolean is_getcode = true;
    private int timecode = 60;

    private String deviceId = "";
    private Timer mTimer;
    private TimerTask mTimerTask;

    String TAG = "RegisterActivity";
    /**
     * 微信登录相关
     */


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_binding);
        initView();
        AndPermission.with(this)
                .runtime()
                .permission(READ_PHONE_STATE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {

                        getToken();
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {

                        Toast.makeText(LoginPhoneActivity.this, "存储权限申请失败！", Toast.LENGTH_SHORT).show();
                        if (AndPermission.hasAlwaysDeniedPermission(LoginPhoneActivity.this, permissions)) {
//                            showSettingDialog(permissions);
                        }
                    }
                })
                .start();
    }


    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }
    private void initView() {
        setStatusBar();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
        tv_home_title = (TextView) findViewById(R.id.tv_home_title);
        tv_login_getcode = (TextView) findViewById(R.id.tv_login_getcode);
        bt_login = findViewById(R.id.bt_login);
        et_login_code = findViewById(R.id.et_login_code);
        et_login_phone = findViewById(R.id.et_login_phone);

        tv_home_title.setText("");
        tv_login_getcode.setOnClickListener(this);
        bt_login.setOnClickListener(this);
        et_login_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    bt_login.setBackground(getResources().getDrawable(R.drawable.background_bg_banyuan_hui));
                    return;
                } else {
                    bt_login.setBackground(getResources().getDrawable(R.drawable.background_bg_banyuan));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {

        super.onPause();

        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login_getcode:
                if (et_login_phone.getText().toString().trim().length() >= 11) {

                    if (is_getcode) {
                        is_getcode=false;
                        getSmsSend();
                        timecode = 60;
                        timeUtils(1);
                    }

                } else {
                    Toast.makeText(getApplicationContext(),"请输入正确的手机号！",Toast.LENGTH_SHORT).show();
//                    ToastUtil.showShort(getApplicationContext(), "请输入正确的手机号！");
                }

                break;

            case R.id.bt_login:
                if (et_login_phone.getText().toString().trim().length() >= 11) {
                    if (et_login_code.getText().toString().trim().length() > 0) {
                        getAuthLogin();
                    } else {
                        Toast.makeText(getApplicationContext(),"请输入验证码",Toast.LENGTH_SHORT).show();
//                        ToastUtil.showShort(getApplicationContext(),"请输入验证码");
                    }

                } else {
                    Toast.makeText(getApplicationContext(),"请输入正确的手机号！",Toast.LENGTH_SHORT).show();
//                    ToastUtil.showShort(getApplicationContext(),"请输入正确的手机号！");
                }


                break;

            default:
                break;

        }
    }


    /**
     * 首页分类
     */
    public void getToken() {

        if (Build.VERSION.SDK_INT >= 23) {
            if (LoginPhoneActivity.this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) ==
                    PackageManager.PERMISSION_GRANTED) {
                TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                deviceId = tm.getDeviceId();
            }
        } else {
            TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            deviceId = tm.getDeviceId();
        }
        Map<String, String> params = new HashMap<>();

        params.put("key", "91MiTang!&)@");

        params.put("deviceId", deviceId);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        String url = NetConfig.AUTH_ACCESS_TOKEN;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        TokenBean packlist = gson.fromJson(response, TokenBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            SharepUtils.setString_info(LoginPhoneActivity.this, packlist.getDatas().getAccessToken(), SharepUtils.USER_ACCESSTOKEN);

                        }
                    }
                });
    }

    /**
     * 首页分类
     */
    public void getSmsSend() {

        Map<String, String> params = new HashMap<>();

        params.put("phone", et_login_phone.getText().toString().trim());

        params.put("deviceId", deviceId);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", SharepUtils.getString_info(LoginPhoneActivity.this, SharepUtils.USER_ACCESSTOKEN));

        String url = NetConfig.SMS_SEND;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        GsonResultok packlist = gson.fromJson(response, GsonResultok.class);
                        int code = packlist.getCode();
                        if (code == 200) {
//                            SharepUtils.setString_info(RegisterActivity.this, packlist.getDatas().getAccessToken(), SharepUtils.USER_ACCESSTOKEN);
                        }
                    }
                });
    }

    /**
     * 首页分类
     */
    public void getAuthLogin() {

        Map<String, String> params = new HashMap<>();

        params.put("phone", et_login_phone.getText().toString().trim());

        params.put("deviceId", deviceId);
        params.put("verifyCode", et_login_code.getText().toString().trim());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        String url = NetConfig.AUTH_LOGIN;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        AuthLoginBean packlist = gson.fromJson(response, AuthLoginBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
//                            SharepUtils.setString_info(RegisterActivity.this, packlist.getDatas().getAccessToken(), SharepUtils.USER_ACCESSTOKEN);
                            AuthLoginBean.DatasBean mUserInfo;
                            mUserInfo = packlist.getDatas();
                            SharepUtils.saveUserInfo(LoginPhoneActivity.this, mUserInfo);

                            List<String> LikeTags1;
                            try {
                                LikeTags1 = SharepUtils.getShDataList(LoginPhoneActivity.this, SharepUtils.USER_FAV_TAGS_LIST, String.class);

                                SharepUtils.setShDataList(LoginPhoneActivity.this, SharepUtils.USER_FAV_TAGS_lOCAL, LikeTags1);
                                List<String> tags = new ArrayList<String>();
                                tags = packlist.getDatas().getUserInfo().getLikeTags();
                                if (tags!=null&&tags.size() > 0) {
                                    List<String> LikeTags = packlist.getDatas().getUserInfo().getLikeTags();
                                    SharepUtils.setShDataList(LoginPhoneActivity.this, SharepUtils.USER_FAV_TAGS_LIST, LikeTags);

                                }
                            } catch (Exception e) {

                            }



                            ToastUtil.showShort(getApplicationContext(), packlist.getMsg());
                            SharepUtils.setString_info(LoginPhoneActivity.this,"1", SharepUtils.USER_IS_LOGIN);
                            finish();
                            ToastUtil.showShort(getApplicationContext(), packlist.getMsg());
                        }else {
                            ToastUtil.showShort(getApplicationContext(), packlist.getMsg());
                        }
                    }
                });
    }

    /**
     * 倒计时的管理
     */
    public void timeUtils(final int type) {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            Runnable updateUI = new Runnable() {
                @Override
                public void run() {
                    updateUIText(type);
                }
            };

            @Override
            public void run() {
                runOnUiThread(updateUI);
            }
        };
        mTimer.schedule(mTimerTask, 0, 1000);
    }

    /**
     * 处理文本的显示
     */
    public void updateUIText(int type) {

        switch (type) {
            case 1:
                timecode--;

                if (timecode < 0) {
                    if (mTimer != null) {
                        mTimer.cancel();
                        mTimer = null;
                    }
                    is_getcode=true;
                    tv_login_getcode.setText("发送验证码");
                } else {
                    tv_login_getcode.setText(timecode + "S后重新获取");
                }

                break;

            default:
                break;
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == 0) {
            String is_ok = data.getStringExtra("is_ok");
            if ("1".equals(is_ok)) {
                finish();
            }


        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

